package com.iotproject.studyservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.iotproject.studyservice.entity.StudyGrade;
import com.iotproject.studyservice.entity.excel.StudyGradeData;
import com.iotproject.studyservice.service.StudyGradeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

public class StudyGradeExcelListener extends AnalysisEventListener<StudyGradeData> {

    StudyGradeService studyGradeService;

    public StudyGradeExcelListener() {
    }

    public StudyGradeExcelListener(StudyGradeService studyGradeService) {
        this.studyGradeService = studyGradeService;
    }

    @Override
    public void invoke(StudyGradeData studyGradeData, AnalysisContext analysisContext) {
        if (studyGradeData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String name = studyGradeData.getName();
        String cover = studyGradeData.getCover();
        StudyGrade studyGrade = existGrade(studyGradeService, name);
        if (studyGrade == null) {//不存在
            studyGrade = new StudyGrade();
            if (StringUtils.isEmpty(cover)) {
                //默认封面地址
                cover = "https://img0.baidu.com/it/u=2582634410,4060861033&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=668";
            }
            studyGrade.setName(name);
            studyGrade.setCover(cover);
            studyGradeService.save(studyGrade);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断类别是否重复
    //可以根据 类别名称name 判断
    public StudyGrade existGrade(StudyGradeService studyGradeService, String name) {
        QueryWrapper<StudyGrade> studyGradeQueryWrapper = new QueryWrapper<>();
        studyGradeQueryWrapper.eq("name", name);
        StudyGrade studyGrade = studyGradeService.getOne(studyGradeQueryWrapper);
        return studyGrade;
    }

}
